<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.testDataCollection_view" @click="viewDetail(row)">详情</el-button>
      </template>
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <el-dialog
      custom-class="scrapRecordQuerydetailDialog"
      v-dragDirectives
      ref="dialog"
      title="详情"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="5vh"
      @close="closeDialog"
    >
      <avue-form v-if="showType === 'P-SCRAP'" :option="scrapDataDetailOption" :table-loading="loading" v-model="scrapDataDetail"></avue-form>
      <avue-form v-if="showType === 'M-SCRAP'" :option="dataDetailOption" :table-loading="loading" v-model="scrapDataDetail">
        <template slot="repairCode">
          <el-input
            v-if="scrapDataDetail.productHandlingResultList"
            type="textarea"
            disabled
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="scrapDataDetail.productHandlingResultList.map((list) => list.resultName).join('；')"
          >
          </el-input>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-product/mro/centerproduct/scrap/page" :option="option" :page="page" :query="query" file-name="报废记录"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail } from '@/api/report/scrap-record-query';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList as getRepairSiteList } from '@/api/repair/repairSite';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
export default {
  name: 'ReportScrapRecordQuery',
  components: {
    CommonModalTemplate,
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'SCARP_RECORD_QUERY',
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {},
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 18,
        labelWidth: 100,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        columnBtn: false,
        searchLabelWidth: 100,
        menuWidth: 100,
        column: [
          {
            label: '条码类型',
            prop: 'objectType',
            search: true,
            searchOrder: 2,
            type: 'select',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ]
          },
          {
            label: '序列号',
            prop: 'productSequenceNumber',
            search: true,
            searchOrder: 3
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 1
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '产线名称',
            prop: 'lineName',
            type: 'select',
            search: true,
            dicUrl: '/api/mes-product/productionline/list',
            props: {
              label: 'name',
              value: 'name'
            }
          },
          {
            label: '报废类型',
            prop: 'scrapType',
            search: true,
            searchOrder: 4,
            type: 'select',
            dicData: [
              {
                label: '产品报废',
                value: 'P-SCRAP'
              },
              {
                label: '维修报废',
                value: 'M-SCRAP'
              },
              {
                label: '库存报废',
                value: 'W-SCRAP'
              }
            ]
          },
          {
            label: '报废登记人',
            prop: 'scrapRegistryByName'
          },
          {
            label: '报废登记时间',
            prop: 'scrapRegistryTime',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
          },
          {
            label: '报废确认人',
            prop: 'createByName'
          },
          {
            label: '报废确认时间',
            prop: 'createTime',
            width: 130,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false
          },
          {
            label: '报废确认时间',
            prop: 'createTimes',
            search: true,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            hide: true
          },
          {
            label: '维修站',
            prop: 'repairCenterName',
            search: true,
            searchOrder: 5,
            hide: true,
            type: 'select',
            dicData: []
          }
        ]
      },
      data: [],
      showDialog: false,
      dataDetailOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '100',
        column: [
          {
            label: '序列号',
            prop: 'productSequenceNumber',
            disabled: true
          },
          {
            label: '条码类型',
            prop: 'objectType',
            disabled: true,
            type: 'select',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ]
          },
          {
            label: '产品数量',
            prop: 'quantity',
            disabled: true
          },
          {
            label: '不良来源',
            prop: 'registrySource',
            disabled: true,
            type: 'select',
            dicData: [
              {
                label: '自动',
                value: 'AUTO'
              },
              {
                label: '手动',
                value: 'MANUAL'
              }
            ]
          },
          {
            label: '当前所处工序',
            prop: 'currentRouteName',
            disabled: true
          },
          {
            label: '不良产生工序',
            prop: 'fromRouteName',
            disabled: true
          },
          {
            label: '不良代码',
            prop: 'failureCode',
            disabled: true
          },
          {
            label: '不良现象描述',
            prop: 'failureName',
            disabled: true
          },
          {
            label: '不良登记人员',
            prop: 'registryByName',
            disabled: true
          },
          {
            label: '不良登记时间',
            prop: 'registryDate',
            disabled: true
          },
          {
            label: '不良原因大类',
            prop: 'mainCauseName',
            disabled: true
          },
          {
            label: '不良原因小类',
            prop: 'subCauseName',
            disabled: true
          },
          {
            label: '不良确认人员',
            prop: 'createByName',
            disabled: true
          },
          {
            label: '不良确认时间',
            prop: 'createTime',
            disabled: true
          },
          {
            label: '不良确认结果',
            prop: 'handlingResult',
            disabled: true,
            row: true,
            type: 'select',
            dicData: [
              {
                label: '产品维修',
                value: 'REPAIR'
              },
              {
                label: '产品报废',
                value: 'SCRAP'
              },
              {
                label: '解除不良',
                value: 'RELIEVE'
              }
            ]
          },
          {
            label: '进维修时间',
            prop: 'repairInTime',
            disabled: true
          },
          {
            label: '维修执行人员',
            prop: 'repairByName',
            disabled: true
          },
          {
            label: '维修代码',
            prop: 'repairCode',
            disabled: true,
            span: 24,
            formslot: true
          },
          {
            label: '维修完成时间',
            prop: 'repairEndTime',
            disabled: true
          },
          {
            label: '维修确认结果',
            prop: 'repairHandlingResult',
            disabled: true,
            row: true,
            type: 'select',
            dicData: [
              {
                label: '重新维修',
                value: 'REMRO'
              },
              {
                label: '维修成功',
                value: 'SUCCESS'
              },
              {
                label: '维修报废',
                value: 'SCRAP'
              }
            ]
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true
          },
          {
            label: '车间',
            prop: 'workshopName',
            disabled: true
          },
          {
            label: '产线',
            prop: 'lineName',
            disabled: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            disabled: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            disabled: true
          },
          {
            label: '报废图片',
            prop: 'imageList',
            type: 'upload',
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            props: {
              value: 'link'
            },
            accept: 'image/png, image/jpeg',
            span: 24,
            listType: 'picture-card',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          }
        ]
      },
      scrapDataDetail: {
        imageList: []
      },
      scrapDataDetailOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '100',
        column: [
          {
            label: '序列号',
            prop: 'productSequenceNumber',
            disabled: true
          },
          {
            label: '条码类型',
            prop: 'objectType',
            disabled: true,
            type: 'select',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ]
          },
          {
            label: '产品数量',
            prop: 'quantity',
            disabled: true
          },
          {
            label: '不良来源',
            prop: 'registrySource',
            disabled: true,
            type: 'select',
            dicData: [
              {
                label: '自动',
                value: 'AUTO'
              },
              {
                label: '手动',
                value: 'MANUAL'
              }
            ]
          },
          {
            label: '当前所处工序',
            prop: 'currentRouteName',
            disabled: true
          },
          {
            label: '不良产生工序',
            prop: 'fromRouteName',
            disabled: true
          },
          {
            label: '不良代码',
            prop: 'failureCode',
            disabled: true
          },
          {
            label: '不良现象描述',
            prop: 'failureName',
            disabled: true
          },
          {
            label: '不良登记人员',
            prop: 'registryByName',
            disabled: true
          },
          {
            label: '不良登记时间',
            prop: 'registryDate',
            disabled: true
          },
          {
            label: '报废类型',
            prop: 'scrapType',
            disabled: true
          },
          {
            label: '报废原因',
            prop: 'remark',
            disabled: true
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true
          },
          {
            label: '车间',
            prop: 'workshopName',
            disabled: true
          },
          {
            label: '产线',
            prop: 'lineName',
            disabled: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            disabled: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            disabled: true
          }
        ]
      },
      showType: ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    let startDate = this.$moment(new Date()).format('YYYY-MM-DD');
    let endDate = this.$moment(new Date()).format('YYYY-MM-DD');
    startDate = startDate + ' ' + '00:00:00';
    endDate = endDate + ' ' + '23:59:59';
    this.$set(this.search, 'createTimes', [startDate, endDate]);
    this.query.createTimes = this.search.createTimes;
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      let urlQuery = this.$route.query;
      if (urlQuery && urlQuery.sequenceNumber && urlQuery.createTime && urlQuery.scrapType) {
        this.search.productSequenceNumber = decodeURIComponent(urlQuery.sequenceNumber);
        let scrapType = decodeURIComponent(urlQuery.scrapType);
        if (scrapType == 'PRODUCT') {
          this.search.scrapType = 'P-SCRAP';
        } else if (scrapType == 'REPAIR') {
          this.search.scrapType = 'M-SCRAP';
        }
        let createTimes = decodeURIComponent(urlQuery.createTime);
        if (createTimes) {
          this.search.createTimes = [createTimes, createTimes];
        }
      }
    });
    const repairCenterName = this.findObject(this.option.column, 'repairCenterName');
    repairCenterName.dicData = [];
    getRepairSiteList(1, 10000, {})
      .then((res) => {
        repairCenterName.dicData = this._get(res, 'data.data.records', []);
        repairCenterName.dicData = this._map(repairCenterName.dicData, (item) => {
          return {
            label: item.name,
            value: item.code
          };
        });
      })
      .catch((err) => {
        repairCenterName.dicData = [];
      });
  },
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.createTimes) {
        params.confirmStartTime = params.createTimes[0];
        params.confirmEndTime = params.createTimes[1];
        delete params.createTimes;
      }
      if (params.repairCenterName) {
        params.repairCenterCode = params.repairCenterName;
        delete params.repairCenterName;
      }
      if (params.scrapRegistryTime) {
        params.confirmStartTime = params.scrapRegistryTime[0];
        params.confirmEndTime = params.scrapRegistryTime[1];
        delete params.scrapRegistryTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.query.createTimes) {
        this.query.confirmStartTime = this.$moment(this.query.createTimes[0]).format('YYYY-MM-DD HH:mm:ss');
        this.query.confirmEndTime = this.$moment(this.query.createTimes[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTimes;
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        delete this.query.createTimes;
      });
    },

    viewDetail(row) {
      this.showType = row.scrapType;
      this.showDialog = true;
      this.testDataDetail = row;
      this.testDataDetailResult = [];
      getDetail(row.id, row.productHandlingId).then(
        (res) => {
          this.scrapDataDetail = this._get(res, 'data.data', {});
        },
        (error) => {
          this.scrapDataDetail = {};
        }
      );
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderNoModal':
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style lang="scss">
.scrapRecordQuerydetailDialog .avue-upload .el-upload--picture-card {
  display: none;
}
</style>
